import { createRouter,createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Layout from "@/views/Layout.vue";

//自定义路由
const routes = [
    //登录页面路由
  {
    path: '/login',
    name: 'Login',
    component: Login,
      meta:{
        title:'管理员登录'
      }
  },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children:[
            {
                path: '/dashboard',
                name: 'Dashboard',
                component: () => import('@/views/Dashboard.vue'),
                meta:{
                    title:'系统首页',
                    activeMenu:'/dashboard'
                }
            },
            {
                path: '/singer',
                name: 'Singer',
                component: () => import('@/views/Singer.vue'),
                meta:{
                    title:'歌手管理',
                    activeMenu:'/singer'
                }
            },
            {
                path: '/consumerList',
                name: 'ConsumerList',
                component: () => import('@/views/ConsumerList.vue'),
                meta:{
                    title:'用户管理',
                    activeMenu:'/consumerList'
                }
            },
            {
                path: '/songList',
                name: 'SongList',
                component: () => import('@/views/SongList.vue'),
                meta:{
                    title:'歌曲列表管理',
                    activeMenu:'/songList'
                }
            },
            {
                path: '/rank',
                name: 'Rank',
                component: () => import('@/views/Rank.vue'),
                meta:{
                    title:'榜单管理',
                    activeMenu:'/rank'
                }
            },
            {
                path: '/rankSong',
                name: 'RankSong',
                component: () => import('@/views/RankSong.vue'),
                meta:{
                    title:'榜单歌曲管理',
                    activeMenu:'/rankSong'
                }
            },
            {
                path: '/song/:id',
                name: 'Song',
                component: () => import('@/views/Song.vue'),
                meta:{
                    title:'歌曲管理',
                    activeMenu:'/song'
                }
            }
        ]
    },

    //默认访问重定向到登录页面
    {
        path: '/',
        redirect: '/login'
    }
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫 - 权限验证
router.beforeEach((to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    // 检查是否已登录（存在 token）
    const token = localStorage.getItem('adminToken')

    // 如果访问的不是登录页且没有 token，则重定向到登录页
    if (to.path !== '/login' && !token) {
        next('/login')
    } else {
        next()
    }
})

export default router